package tech.anzhen.simple.rpc.support;

import tech.anzhen.simple.rpc.support.exception.RemoteException;
import tech.anzhen.simple.rpc.support.rest.RestProxyFactoryBean;
import tech.anzhen.simple.rpc.support.exception.BaseException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * @author anz
 */
public class RemoteServiceProxyFactoryBean<T> extends RemoteServiceProxyFactorySupport<T> implements InitializingBean, EnvironmentAware {
    protected boolean eurekaClientRegister;
    private Environment environment;
    private String systemName;

    protected String defaultRemoteAddress;

    protected Integer connectTimeout;

    protected Integer readTimeout;

    protected String identity;

    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }

    public void setDefaultRemoteAddress(String defaultRemoteAddress) {
        this.defaultRemoteAddress = defaultRemoteAddress;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setReadTimeout(Integer readTimeout) {
        this.readTimeout = readTimeout;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }


    @Override
    protected T getRemoteProxy() {

        try {
            Properties properties = new Properties();
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("service-address.properties"));
            String remoteAddress = properties.getProperty(systemName);

            T remoteService = null;
            if (remoteAddress.startsWith("rest:")) {
                remoteAddress = remoteAddress.substring("rest:".length());
                RestProxyFactoryBean<T> bean = new RestProxyFactoryBean<T>();
                bean.setServiceInterface(serviceInterface);
                bean.setBaseAddress(remoteAddress);
                bean.setConnectTimeout(connectTimeout);
                bean.setReadTimeout(readTimeout);
                bean.setDefaultIdentity(identity);
                try {
                    remoteService = bean.getObject();
                } catch (Exception e) {
                    throw new RemoteException(e);
                }
            }

            if (remoteService == null) {
                throw new BaseException("无法创建远程服务:" + remoteAddress);
            }
            return remoteService;
        } catch (Exception e) {
            throw new BaseException("无法创建远程服务", e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        eurekaClientRegister = environment.getProperty("remoting.rest.register", Boolean.class, Boolean.FALSE);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
}
